package ai.people.netmon.twitter.probe.service.impl;

import ai.people.core.standard.fill.entity.Msg;
import ai.people.core.standard.fill.service.SendNewAccountToTopicService;
import ai.people.core.standard.gather.service.AccountGatherSyncService;
import ai.people.netmon.framework.businessenum.ImportanceDegEnum;
import ai.people.netmon.framework.businessenum.NewAccountNeedFillTopicEnum;
import ai.people.netmon.framework.businessenum.gather.GatherStatusEnum;
import ai.people.netmon.framework.constant.SourceCollectionConstant;
import ai.people.netmon.framework.domain.gather.config.GatherSyncExtended;
import ai.people.netmon.framework.domain.twitter.probe.entity.TwitterAccount;
import ai.people.netmon.framework.domain.twitter.probe.request.UserWebRequest;
import ai.people.netmon.framework.domain.twitter.probe.vo.TwitterAccountVO;
import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.framework.utils.AssertUtils;
import ai.people.netmon.twitter.probe.mapper.TwitterAccountMapper;
import ai.people.netmon.twitter.probe.service.TwitterUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 用户服务impl
 *
 * @author yuanqinglong
 * @date 2022/2/25 10:37
 */
@Service
@Slf4j
public class TwitterUserServiceImpl extends ServiceImpl<TwitterAccountMapper, TwitterAccount> implements TwitterUserService, AccountGatherSyncService<TwitterAccount>, SendNewAccountToTopicService {

    @Autowired
    private TwitterAccountMapper twitterCollectConfigAccountMapper;

    @Value("${data-sync-url}")
    private String dataSyncUrl;
    @Autowired
    ExecutorService pool;
    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    TwitterAccountMapper mapper;

    /**
     * 获取用户
     *
     * @param id id
     * @return {@link TwitterAccountVO}
     */
    @Override
    public TwitterAccount getUser(Long id) {
        return getById(id);
    }

    /**
     * 保存twitter用户
     *
     * @param twitterAccount twitter账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTwitterUser(TwitterAccount twitterAccount) {
        if (StringUtils.isBlank(twitterAccount.getCollectionFrequency())) {
            twitterAccount.setCollectionFrequency(SourceCollectionConstant.COLLECTION_FREQUENCY_STR);
        }
        twitterAccount.setCollectionStatus(GatherStatusEnum.TO_BE_COLLECTED.getCode());
        int insertResult = twitterCollectConfigAccountMapper.insert(twitterAccount);
        AssertUtils.isTrue(insertResult > 0, CommonEnum.FAIL);
    }


    /**
     * 批量保存twitter用户
     *
     * @param list twitter账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveTwitterUser(List<TwitterAccount> list) {
        AssertUtils.isTrue(!CollectionUtils.isEmpty(list), CommonEnum.FAIL);
        log.info("接收数据条数:{}",list.size());
        //前置处理1、去掉account_name为空的 2、修改采集状态
        list = list.stream().filter(item -> Objects.nonNull(item) && StringUtils.isNotBlank(item.getAccountName()))
                .peek(x -> {
                    x.setCollectionStatus(GatherStatusEnum.TO_BE_COLLECTED.getCode());
                    if (StringUtils.isBlank(x.getCollectionFrequency())) {
                        x.setCollectionFrequency(SourceCollectionConstant.COLLECTION_FREQUENCY_STR);
                    }
                }).collect(Collectors.toList());
        log.info("过滤为空数据条数:{}",list.size());
        List<String> accountNames = list.stream().map(TwitterAccount::getAccountName).collect(Collectors.toList());
        LambdaQueryWrapper<TwitterAccount> queryWrapper = Wrappers.lambdaQuery();
        //去数据库查询一遍哪些重复
        List<TwitterAccount> already = this.list(queryWrapper.select(TwitterAccount::getAccountName).in(TwitterAccount::getAccountName, accountNames));
        if (!CollectionUtils.isEmpty(already)) {
            //删除重复的
            Set<String> alreadyName = already.stream().map(TwitterAccount::getAccountName).collect(Collectors.toSet());
            list = list.stream().filter(twitterAccount -> !alreadyName.contains(twitterAccount.getAccountName())).distinct().collect(Collectors.toList());
        }
        log.info("过滤重复后剩余数据条数:{}",list.size());
        if (!CollectionUtils.isEmpty(list)) {
            boolean saveResult = this.saveBatch(list);
            log.info("批量保存条数:{}", list.size());
            AssertUtils.isTrue(saveResult, CommonEnum.FAIL);
            //推送kafka
            List<Msg> msgList = new ArrayList<>();
            list.forEach(twitterAccount -> msgList.add(new Msg(twitterAccount)));
            this.sendNewAccountData(NewAccountNeedFillTopicEnum.NEW_ACCOUNT_NEED_FILL_TWITTER.name(), msgList, kafkaTemplate);
        }
    }

    /**
     * 更新twitter用户
     *
     * @param newData twitter账户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTwitterUser(TwitterAccount newData) {
        Long id = newData.getId();
        AssertUtils.isNotNull(id, CommonEnum.CHECK_NOT_EMPTY_PRIMARY_ID);
        String newImportanceDeg = newData.getImportanceDeg();
        int ordinaryCode = ImportanceDegEnum.ORDINARY.getCode();
        if (StringUtils.isNotBlank(newImportanceDeg) && Integer.parseInt(newImportanceDeg) >= ordinaryCode) {
            TwitterAccount old = this.getById(id);
            update(newData);
            Integer oldImportanceDeg = Optional.ofNullable(old.getImportanceDeg()).map(Integer::valueOf).orElse(ordinaryCode);
            if (Integer.parseInt(newImportanceDeg) >= oldImportanceDeg) {
                this.syncGatherAccount(Collections.singletonList(getById(id)), dataSyncUrl, new GatherSyncExtended());
            }
        }else{
            update(newData);
        }
    }

    private void update(TwitterAccount newData) {
        newData.setUpdateTime(OffsetDateTime.now());
        boolean updateResult = this.updateById(newData);
        AssertUtils.isTrue(updateResult, CommonEnum.FAIL);
    }


    /**
     * twitter账户列表
     *
     * @param userRequest 用户请求
     * @return {@link PageResponse}<{@link TwitterAccount}>
     */
    @Override
    public PageResponse<TwitterAccount> listTwitterAccounts(UserWebRequest userRequest) {
        Page<TwitterAccount> twitterAccountPage = new Page<>(userRequest.getOriginPageNo(), userRequest.getPageSize());
        IPage<TwitterAccount> selectPage = mapper.listTwitterAccountPage(twitterAccountPage, userRequest);
        return PageResponse.builder(selectPage);
    }


    /**
     * 更新集合状态
     *
     * @param twitterAccounts 账户
     */
    @Override
    public void updateCollectionStatus(List<TwitterAccount> twitterAccounts) {
        OffsetDateTime updateTime = OffsetDateTime.now();
        twitterAccounts.forEach(twitterAccount -> {
            twitterAccount.setCollectionStatus(GatherStatusEnum.COLLECTED.getCode());
            twitterAccount.setUpdateTime(updateTime);
        });
        this.updateBatchById(twitterAccounts);
    }
}
